package com.mall.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

//用来操作Cookie的工具类
public class CookieUtil {

    /***
     * 向浏览器设置cookie
     * @param response 响应对象
     * @param key
     * @param value
     */
    public static void setCookie(HttpServletResponse response,String key,String value) throws UnsupportedEncodingException {
        //这里需要对value进行编码，防止有特殊字符导致存储失败
        Cookie cookie = new Cookie(key, URLEncoder.encode(value,"UTF-8"));
        response.addCookie(cookie);
    }

    /***
     * 获取指定cookie
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request,String key) throws UnsupportedEncodingException {
        //获取所有cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            //遍历cookie找到需要的cookie
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(key)){
                    //由于存储的时候进行了编码，所以取出的时候要进行解码
                    return URLDecoder.decode(cookie.getValue(),"UTF-8");
                }
            }
        }
        //没有找到就返回空
        return null;
    }

    /***
     * 获取所有的Cookie
     * @param request
     * @return
     */
    public static Cookie[] getAllCookies(HttpServletRequest request){
        return request.getCookies();
    }

    /***
     * 从cookie中删除key的cookie
     * @param response
     * @param key
     */
    public static void deleteCookie(HttpServletResponse response,String key){
        Cookie cookie = new Cookie(key,null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
